package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.enviaEmail;
import bean.empresaBean;
import bean.funcionarioBean;
import conexao.Conexao;
import dao.empresaDao;
import dao.funcionarioDao;

public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public loginServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		response.setCharacterEncoding("UTF-8");
		request.setCharacterEncoding("UTF-8");
		
		PrintWriter out = response.getWriter();
		
		Connection conn = null;
		try {
			conn = new Conexao().getConexao();
		} catch (SQLException e) {
			new enviaEmail().enviar(e);
			out.print("falhaConexao");
			return;
		}

		String login = request.getParameter("login");
		String senha = request.getParameter("senha");
		
		try {
			funcionarioBean funcionario = new funcionarioDao().validaLogin(
					conn, login, senha);

			if (funcionario.getId() != null) {
				if(funcionario.getIdFuncao() != 6){
					if(new empresaDao().isAtivo(conn, funcionario.getIdEmpresa())){
						request.getSession().setAttribute("id", funcionario.getId());
						request.getSession().setAttribute("nome", funcionario.getNome());
						request.getSession().setAttribute("sexo", funcionario.getSexo());
						request.getSession().setAttribute("idfuncao", funcionario.getIdFuncao());
						request.getSession().setAttribute("idempresa", funcionario.getIdEmpresa());
					}else{
						out.print("Empresa desativada.");
						return;
					}
				}else{
					request.getSession().setAttribute("id", funcionario.getId());
					request.getSession().setAttribute("nome", funcionario.getNome());
					request.getSession().setAttribute("sexo", funcionario.getSexo());
					request.getSession().setAttribute("idfuncao", funcionario.getIdFuncao());
					empresaBean empresa = new empresaDao().getMin(conn);
					request.getSession().setAttribute("idempresa", empresa.getId());
				}

			} else {
				out.println("Login ou Senha incorreto!");
			}
		} catch (Exception e) {
			try {
				conn.rollback();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
				ex.printStackTrace();}
				new enviaEmail().enviar(e);
				throw new RuntimeException(e);
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {
				new enviaEmail().enviar(ex);
			}
		}

	}

}
